package com.zyb.learn.springboot.learnzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: zyb
 * @Date: 2018/11/8 09:25
 * @Description: Zuul做访问前的权限校验
 */
@Component
public class PreFilter extends ZuulFilter {
    Logger logger = LoggerFactory.getLogger(PreFilter.class);

    //拦截的方式,前置,后置等
    @Override
    public String filterType() {
        return "pre";
    }

    //多个拦截器共存时,执行的优先级
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否启用拦截
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //拦截的具体逻辑
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String accessToker = request.getParameter("accessToker");
        if (StringUtils.isEmpty(accessToker)) {
            logger.info("请求中 accessToker 为空,无法访问!");
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            currentContext.setResponseBody("this data is change by zyb");
        } else {
            logger.info("请求权限验证成功, accessToker 已匹配");
        }
        return null;
    }
}
